//
//  SEConfirmReservePayView.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/7.
//

import UIKit

struct SEConfirmReservePayViewModel {
    var price: String = ""
    var time: String = ""
    var agree: Bool = false
}

enum SEConfirmReservePayViewActionType {
    case agree
    case showInfo
    case pay
}

protocol SEConfirmReservePayViewDelegate: NSObjectProtocol {
    func confirmReservePayViewBtnAction(_ payView: SEConfirmReservePayView, with actionType: SEConfirmReservePayViewActionType)
}

@IBDesignable class SEConfirmReservePayView: UIView {

    var view: UIView!
    weak var delegate: SEConfirmReservePayViewDelegate?
    
    @IBOutlet weak var agreeBtn: UIButton!
    @IBOutlet private weak var priceLabel: UILabel!
    @IBOutlet private weak var timeLabel: UILabel!
    @IBOutlet weak var payBtn: UIButton! {
        didSet {
            payBtn.isIgnoreEvent = false
        }
    }


    // MARK: - action event
    
    @IBAction private func agreeAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        delegate?.confirmReservePayViewBtnAction(self, with: .agree)
    }
    
    @IBAction private func showInfoForPatients() {
        delegate?.confirmReservePayViewBtnAction(self, with: .showInfo)
    }
    
    @IBAction private func payAction() {
        delegate?.confirmReservePayViewBtnAction(self, with: .pay)
    }
    
    // MARK: - life cycle
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        view = loadViewFromNib()
    }

    func updateView(with model: SEConfirmReservePayViewModel) {
        priceLabel.text = "合计: \(model.price)元"
        agreeBtn.isSelected = model.agree
        timeLabel.text = model.time
    }
    
    // MARK: - load view from xib
    
    private func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName(), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(view)

        return view
    }

    private func nibName() -> String {
        return String(describing: type(of: self))
    }
}
